package cn.simple.filetools.poi.excel.support;

import cn.simple.filetools.annotation.Excel;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.lang.reflect.Field;

/**
 * @author jiangjinjian
 * @date 2024/8/28 10:05
 * @description 默认po-excel写出处理器
 */
public class DefaultPoiExcelWriteProcessor<T> extends AbstractPoiExcelWriteProcessor<T> {

    @Override
    protected XSSFSheet createSheet(XSSFWorkbook wb) {
        return wb.createSheet("测试sheet");
    }

    @Override
    protected void writeRow(T data, Row row, Sheet sheet) {
        Field[] fields = data.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            field.setAccessible(true);
            Cell cell = row.createCell(i);
            try {
                cell.setCellValue(String.valueOf(field.get(data)));
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    protected void writeHead(Class<T> tClass, Row row) {
        Field[] fields = tClass.getDeclaredFields();
        int i = 0;
        for (Field field : fields) {
            Cell cell = row.createCell(i++);
            field.setAccessible(true);
            Excel annotation = field.getAnnotation(Excel.class);
            if (annotation == null) {
                continue;
            }
            cell.setCellValue(annotation.value());
        }
    }
}
